﻿using AbpPcClient.WpfClient.Common;
using AbpPcClient.WpfClient.Service.Common;
using AbpPcClient.WpfClient.Service.Login;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbpPcClient.WpfClient.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {

        public string Title { get; set; } = "登录";

        public LoginViewModel(LoginService loginService, IEventAggregator aggregator)
        {
            ExecuteCommand = new DelegateCommand<string>(Execute);
            this.loginService = loginService;
            this.aggregator = aggregator;
        }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            LoginOut();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        { }

        public DelegateCommand<string> ExecuteCommand { get;  private set; }

        private string userName;
        public string Username
        {
            get { return userName; }
            set
            {
                userName = value;
                RaisePropertyChanged();  //双向绑定通知
            }
        }




        private string password;
        private readonly LoginService loginService;
        private readonly IEventAggregator aggregator;

        public string Password
        {
            get { return password; }
            set { password = value; RaisePropertyChanged(); }
        }
        void Execute(string arg)
        {
            switch (arg)
            {
                case "login":Login();break;
                case "loginOut": LoginOut();break;
            }
        }
        void Login()
        {
            if (string.IsNullOrEmpty(userName))
            {
                return;
            };
            if (string.IsNullOrEmpty(password))
            {
                return;
            };
            ResultModel result = loginService.Login(userName, password);
            if (result != null && result.Success)
            {
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            }
            else
            {
                //登录失败提示...
                aggregator.SendMessage(result.Error==null?"":result.Error.Message, "Login");
            }
        }
        void LoginOut()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));
        }

    }
}
